﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EPiServer.Data.Dynamic;
using EPiServer.Data;

namespace EPiServer.DdsPageProvider
{
	public class PropertyRepository
	{
		DynamicDataStore store;

		public PropertyRepository(DynamicDataStore dataStore)
		{
			this.store = dataStore;
		}



		public PropertyBag GetOrCreatePropertyBag(Identity nodeId)
		{
			return GetByNodeId(nodeId) ?? Create(nodeId);
		}

		public PropertyBag Get(Identity id)
		{
			return store.LoadAsPropertyBag(id);
		}

		public PropertyBag GetByNodeId(Identity nodeId)
		{
			return store.ItemsAsPropertyBag().Where(pb => (Identity)pb["NodeId"] == nodeId).Peek();
		}

		public PropertyBag Create(Identity nodeId)
		{
			var bag = new PropertyBag();
			foreach (var mapping in store.StoreDefinition.MappingNames)
			{
				bag[mapping] = null;
			}
			bag["NodeId"] = nodeId;
			return bag;
		}

		public Identity Save(PropertyBag bag)
		{
			return store.Save(bag);
		}

		public void Delete(Identity id)
		{
			store.Delete(id);
		}
	}
}
